# Python学习展示项目 - Docker配置文件
# 多阶段构建，优化镜像大小和安全性

# ==========================================
# 构建阶段
# ==========================================
FROM python:3.11-slim as builder

# 设置构建参数
ARG BUILD_ENV=production

# 设置工作目录
WORKDIR /app

# 安装系统依赖
RUN apt-get update && apt-get install -y \
    build-essential \
    curl \
    && rm -rf /var/lib/apt/lists/*

# 升级pip和安装构建工具
RUN pip install --no-cache-dir --upgrade pip setuptools wheel

# 复制依赖文件
COPY requirements.txt .

# 安装Python依赖到临时目录
RUN pip install --no-cache-dir --user -r requirements.txt

# ==========================================
# 运行阶段
# ==========================================
FROM python:3.11-slim as runtime

# 设置环境变量
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PATH="/home/appuser/.local/bin:$PATH" \
    PYTHONPATH="/app"

# 创建非root用户
RUN groupadd --gid 1000 appgroup && \
    useradd --uid 1000 --gid appgroup --shell /bin/bash --create-home appuser

# 安装运行时系统依赖
RUN apt-get update && apt-get install -y \
    curl \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# 设置工作目录
WORKDIR /app

# 从构建阶段复制Python包
COPY --from=builder /root/.local /home/appuser/.local

# 复制应用代码
COPY --chown=appuser:appgroup . .

# 创建必要的目录
RUN mkdir -p /app/logs /app/uploads /app/data && \
    chown -R appuser:appgroup /app

# 切换到非root用户
USER appuser

# 健康检查
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

# 暴露端口
EXPOSE 8000

# 启动命令
CMD ["uvicorn", "web_framework_comparison.01_fastapi_basic:app", "--host", "0.0.0.0", "--port", "8000"]

# ==========================================
# 开发环境镜像
# ==========================================
FROM runtime as development

# 切换回root用户安装开发依赖
USER root

# 复制开发依赖文件
COPY requirements-dev.txt .

# 安装开发依赖
RUN pip install --no-cache-dir -r requirements-dev.txt

# 安装开发工具
RUN apt-get update && apt-get install -y \
    git \
    vim \
    htop \
    && rm -rf /var/lib/apt/lists/*

# 切换回应用用户
USER appuser

# 开发环境启动命令（带重载）
CMD ["uvicorn", "web_framework_comparison.01_fastapi_basic:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]

# ==========================================
# 生产环境镜像
# ==========================================
FROM runtime as production

# 安装生产服务器
RUN pip install --no-cache-dir gunicorn[gevent]

# 生产环境启动命令
CMD ["gunicorn", "web_framework_comparison.01_fastapi_basic:app", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000"]

# ==========================================
# 镜像元数据
# ==========================================
LABEL maintainer="Python学习展示项目" \
      version="1.0.0" \
      description="Python学习展示项目的Docker镜像" \
      org.opencontainers.image.source="https://github.com/your-repo/pythonLearnShow" \
      org.opencontainers.image.documentation="https://github.com/your-repo/pythonLearnShow/blob/main/README.md"